import Vue from "vue";
import VueRouter from "vue-router";

// 引入组件
import Index from "../views/Index.vue";
import Room from "../views/Room.vue";
import Grade from "../views/Grade.vue";
import Student from "../views/Student.vue";

// 引入 store 对象，用于读取 state 信息
import store from "../store";

Vue.use(VueRouter);

const routes = [
    {
        path: "/login",
        component: () => import("../views/Login.vue"),
    },
    {
        path: "/",
        component: Index,
        children: [
            {
                path: "/grade",
                component: Grade,
            },
            {
                path: "/room",
                component: Room,
            },
            {
                path: "/student",
                component: Student,
            },
        ],
    },
];

// 路由实例
const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,
});

// 路由实例的 beforeEach 来实现路由守卫
// 接收一个回调函数，在每次页面跳转前，执行
router.beforeEach((to, from, next) => {
    // console.log("to", to);
    // console.log("from", from);
    // console.log("next", next);

    // 记得一定要调用 next 函数，否则就是空白页面
    // next();
    if (to.path === "/login" || store.state.user.token) {
        next();
    } else {
        next("/login");
    }
});

export default router;
